<template>
  <div id="funding-details">
    <div class="search-box">
      <el-form>
        <el-form-item label="计划ID：">
          <el-input placeholder="请输入计划ID" v-model="searchForm.planCode" size="small" clearable></el-input>
        </el-form-item>
        <el-form-item label="任务ID：">
          <el-input placeholder="请输入任务ID" v-model="searchForm.taskCode" size="small" clearable></el-input>
        </el-form-item>
        <el-form-item label="时间 ：">
          <el-date-picker format="yyyy-MM-dd HH:mm:ss" value-format="timestamp" size="small" v-model="searchTime"
                          @change="changeTime" type="datetimerange" range-separator="至" start-placeholder="开始日期"
                          end-placeholder="结束日期" :picker-options="pickerOptions"
                          :default-time="['00:00:00', '23:59:59']"></el-date-picker>
        </el-form-item>
        <el-form-item label="财务类型 ：">
          <el-select v-model="searchForm.financeType" placeholder="请选择类型" size="small" clearable>
            <el-option v-for="(item, index) in financeTypeData" :key="index" :label="item.label"
                       :value="item.id"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button class="search-btn" icon="el-icon-ali-search" @click="searchData">查&nbsp;询</el-button>
        </el-form-item>
        <el-form-item>
          <el-button class="reset-btn" icon="el-icon-ali-reset" @click="resetSearchParam">重&nbsp;置</el-button>
        </el-form-item>
      </el-form>
    </div>
    <div class="table-box">
      <el-table border :data="tableData" max-height="580px">
        <el-table-column prop="platform_type" label="店铺类型/店铺名称">
          <div slot-scope="scope">
            <div class="textColor">{{ getShopType(scope.row) }}</div>
            <div>{{ scope.row.shop_name }}</div>
          </div>
        </el-table-column>
        <el-table-column prop="task_code" label="任务ID"></el-table-column>
        <el-table-column prop="capital_change" label="收支" :formatter="getCapitalDetail"></el-table-column>
        <el-table-column prop="capital_change" label="本金/佣金/额外佣金" :formatter="getMoney"></el-table-column>
        <el-table-column prop="freeze_balance" label="冻结余额"></el-table-column>
        <el-table-column prop="capital_balance" label="余额"></el-table-column>
        <el-table-column prop="recharge_balance" label="充值待审核"></el-table-column>
        <el-table-column prop="finance_type" label="财务类型" :formatter="getFinanceType"></el-table-column>
        <el-table-column prop="create_time" sortable label="时间 "></el-table-column>
      </el-table>
      <el-table :data="allTableData" id="exportTable" v-show="false" border>
        <el-table-column prop="shop_type" label="店铺类型" :formatter="getShopType"></el-table-column>
        <el-table-column prop="shop_name" label="店铺名称"></el-table-column>
        <el-table-column prop="task_code" label="任务ID"></el-table-column>
        <el-table-column prop="capital_change" label="收支" :formatter="getCapitalDetail"></el-table-column>
        <el-table-column prop="capital_change" label="本金/佣金/额外佣金" :formatter="getMoney"></el-table-column>
        <el-table-column prop="freeze_balance" label="冻结余额"></el-table-column>
        <el-table-column prop="capital_balance" label="余额"></el-table-column>
        <el-table-column prop="recharge_balance" label="充值待审核"></el-table-column>
        <el-table-column prop="finance_type" label="财务类型" :formatter="getFinanceType"></el-table-column>
        <el-table-column prop="create_time" sortable label="时间 "></el-table-column>
      </el-table>
      <div class="table-footer">
        <el-button icon="el-icon-download" class="download-btn" @click="downloadExcel">导出</el-button>
        <el-pagination :page-sizes="[5, 10, 15, 20]" :page-size="searchForm.pageSize" :current-page="searchForm.page"
                       layout="total, sizes, prev, pager, next, jumper"
                       :total="pageToatal" @size-change="handleSizeChange"
                       @current-change="handleCurrentChange"></el-pagination>
      </div>
    </div>
  </div>
</template>

<script>
import {
  apiGetMerchantShopList,
  apiMerchantCapitalFlow
} from '../../request/api.js'

export default {
  data() {
    return {
      searchForm: {
        token: '',
        page: 1,
        pageSize: 10,
        taskCode: '',
        planCode: '',
        financeType: '',
        startTime: '',
        endTime: ''
      },
      searchTime: [],
      shopNameList: [],
      shopNameOptions: [],
      financeTypeData: [
        {id: 1, label: '销量推广本金佣金扣除'},
        {id: 2, label: '销量推广冻结本金佣金扣除'},
        // {id:3,label:'推手销量任务收入本金佣金'},
        // {id:4,label:'师傅销量任务收入佣金'},
        // {id:5,label:'师公销量任务收入佣金'},
        // {id:6,label:'平台销量佣金收入'},
        {id: 7, label: '销量推广本金佣金退还'},
        // {id:8,label:'推手销量任务退还本金佣金'},
        // {id:9,label:'师父销量佣金退还'},
        // {id:10,label:'师公销量佣金退还'},
        // {id:11,label:'平台销量佣金退还'},
        {id: 12, label: '销量审核失败本金佣金退还'},
        {id: 13, label: '充值冻结增加'},
        {id: 14, label: '充值审核通过余额增加'},
        {id: 15, label: '充值审核失败冻结余额减少'},
        {id: 16, label: '流量推广佣金扣除'},
        {id: 17, label: '流量推广冻结佣金扣除'},
        // {id:18,label:'推手流量任务收入本金佣金'},
        // {id:19,label:'平台流量佣金收入'},
        {id: 20, label: '流量推广佣金退还'},
        // {id:21,label:'推手流量任务退还本金佣金'},
        // {id:22,label:'平台销量佣金退还'},
        {id: 23, label: '流量审核失败'},
        // {id:24,label:'推手本金提现成功扣款'},
        // {id:25,label:'推手本金提现失败退还'},
        // {id:26,label:'推手佣金提现成功扣款'},
        // {id:27,label:'推手佣金提现失败退还'},
        {id: 28, label: '管理员操作'},
        {id: 29, label: '提现余额减少冻结余额增加'},
        {id: 30, label: '提现审核通过冻结余额减少'},
        {id: 31, label: '提现审核失败冻结余额减少余额增加'},
        {id: 32, label: '商家评价推广本金扣除'},
        {id: 33, label: '商家评价推广冻结本金扣除'},
        {id: 36, label: '商家评价推广佣金退还'},
        {id: 39, label: '评价任务审核失败'},
        {id: 55, label: '售后'},
        {id: 58, label: '评价任务超时终止回退'},
        {id: 61, label: '小红书创建评论任务佣金冻结'},
        {id: 62, label: '小红书结算评论任务冻结佣金扣除'},
        {id: 63, label: '小红书评论任务商家佣金退还'},
        {id: 64, label: '小红书评论任务推手收入佣金'},
        {id: 65, label: '小红书评论任务推手佣金退还'},
        {id: 66, label: '小红书评论平台佣金收入'},
        {id: 67, label: '小红书评论任务平台佣金退还'},
        {id: 68, label: '小红书评论任务审核失败'},
      ],
      platformNameObject: {
        1: '淘宝',
        2: '天猫',
        3: '京东',
        4: '1688',
        13: '唯品会',
        15: '拼多多',
        20: '抖音',
        21: '小红书'
      },
      entranceType: {
        1: '关键词',
        2: '淘口令',
        3: '二维码',
        4: '直播',
        5: '其他'
      },
      pageToatal: 0,
      tableData: [],
      allTableData: [],
      pickerOptions: {
        disabledDate(time) {
          let merchantTime = window.localStorage.getItem('merchantTime')
          let curDate = (new Date()).getTime();
          let three = merchantTime * 24 * 3600 * 1000;
          let threeMonths = curDate - three;
          return time.getTime() < threeMonths;
        },
      },
      userToken: window.localStorage.getItem('token')
    }
  },
  created() {
    this.searchForm.token = this.userToken
    this.getShopList()
    this.getTableData()
  },
  methods: {
    dataFilter(val) {
      this.searchForm.shopId = val;
      if (val) { //val存在
        this.shopNameList = this.shopNameOptions.filter((item) => {
          if (!!~item.name.indexOf(val) || !!~item.name.toUpperCase().indexOf(val.toUpperCase())) {
            return true
          }
        })
      } else { //val为空时，还原数组
        this.shopNameList = this.shopNameOptions;
      }
    },
    getShopList() {
      this.$isClick(true);
      apiGetMerchantShopList({
        token: this.userToken
      }).then(res => {
        this.$isClick(false);
        if (res.code == 1) {
          for (var i in res.msg.merchant_shop_list) {
            this.shopNameOptions.push({
              name: this.platformNameObject[res.msg.merchant_shop_list[i].type] + '-' + res.msg.merchant_shop_list[i].name,
              id: res.msg.merchant_shop_list[i].id
            })
          }
          this.shopNameList = this.shopNameOptions
        } else {
          this.$message.error(res.msg);
        }
      }).catch(res => {
        this.$isClick(false);
        this.$message.error(res.msg)
      })
    },
    getTableData() {
      this.$isClick(true);
      apiMerchantCapitalFlow(this.searchForm).then(res => {
        this.$isClick(false);
        if (res.code == 1) {
          this.tableData = res.msg.res
          this.pageToatal = res.msg.con
        } else {
          this.$message.error(res.msg);
        }
      }).catch(res => {
        this.$isClick(false);
        this.$message.error(res.msg)
      })
    },
    getFinanceType(row) {
      for (var i in this.financeTypeData) {
        if (this.financeTypeData[i].id == row.finance_type) {
          if (row.remark) {
            return this.financeTypeData[i].label + '[' + row.remark + ']'
          }
          return this.financeTypeData[i].label
        }
      }
    },
    getShopType(row) {
      return this.platformNameObject[row.shop_type]
    },
    getCapitalDetail(row) {
      var all = parseFloat(row.capital_change) + parseFloat(row.commission_change) + parseFloat(row.extra_commission_change)
      return all.toFixed(2)
    },
    getMoney(row) {
      return row.capital_change + '/' + row.commission_change + '/' + row.extra_commission_change
    },
    searchData() {
      this.searchForm.page = 1
      this.searchForm.pageSize = 10
      this.getTableData()
    },
    resetSearchParam() {
      this.searchForm = {
        token: this.userToken,
        page: 1,
        pageSize: 10,
        shopId: '',
        planType: '',
        taskCode: '',
        planCode: '',
        financeType: '',
        startTime: '',
        endTime: ''
      }
    },
    handleSizeChange(val) {
      this.searchForm.pageSize = val;
      this.getTableData()
    },
    handleCurrentChange(val) {
      this.searchForm.page = val;
      this.getTableData()
    },
    changeOverTimeType(row) {
      if (row.over_time == 0 || row.over_time == '' || row.over_time == null) {
        return '--'
      }
      if (typeof (row.over_time) != 'number') {
        return row.over_time
      }
      var date = new Date(row.over_time * 1000); //时间戳为10位需*1000，时间戳为13位的话不需乘1000
      return this.getFormatTime(date)
    },
    getFormatTime(date) {
      var Y = date.getFullYear() + '-';
      var M = (date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1) + '-';
      var D = (date.getDate() < 10 ? '0' + date.getDate() : date.getDate()) + ' ';
      var h = (date.getHours() < 10 ? '0' + date.getHours() : date.getHours()) + ':';
      var m = (date.getMinutes() < 10 ? '0' + date.getMinutes() : date.getMinutes()) + ':';
      var s = (date.getSeconds() < 10 ? '0' + date.getSeconds() : date.getSeconds());
      return Y + M + D + h + m + s;
    },
    changeTime(val) {
      if (this.searchTime == null) {
        this.searchForm.startTime = ''
        this.searchForm.endTime = ''
      } else {
        this.searchForm.startTime = this.changeTimeType(val[0])
        this.searchForm.endTime = this.changeTimeType(val[1])
      }
    },
    changeTimeType(time) {
      var d = new Date(time);
      var s = d.getFullYear() + '-' + (d.getMonth() + 1) + '-' + d.getDate() + ' ' + d.getHours() + ':' + d.getMinutes() + ':' + d.getSeconds();
      return new Date(s).getTime() / 1000;
    },
    getAllTableData() {
      let data = JSON.parse(JSON.stringify(this.searchForm))
      data.page = 1
      data.pageSize = this.pageToatal
      if (data.pageSize == 0) {
        this.$message.error('当前表格没有数据可以导出');
        return
      }
      return new Promise((resolve) => {
        this.$isClick(true);
        apiMerchantCapitalFlow(data).then(res => {
          this.$isClick(false);
          if (res.code == 1) {
            this.allTableData = res.msg.res
            resolve(res);
          } else {
            this.$message.error(res.msg);
          }
        }).catch(res => {
          this.$isClick(false);
          this.$message.error(res.msg)
        })
      })

    },
    downloadExcel() {
      // this.$loading.show('下载中')
      // var wb = ''
      //  var xlsxParam = { raw: true }
      //  this.getAllTableData().then(()=>{
      //  wb = this.XLSX.utils.table_to_book(document.querySelector('#exportTable'),xlsxParam)
      //  var wbout = this.XLSX.write(wb, { bookType: 'xlsx', bookSST: true, type: 'array' })
      //  try {
      //    this.FileSaver.saveAs(new Blob([wbout], { type: 'application/octet-stream' }),'资金明细.xlsx')
      //  } catch (e) { if (typeof console !== 'undefined') console.log(e, wbout) }
      //  setTimeout(() => {
      //    this.$loading.hide()
      //    this.$message.success('下载完成')
      //  }, 1000);
      //  return wbout
      // })
      this.$loading.show('下载中')
      let downloadUrl = this.BASE_API_URL + 'baseapi/merchant/exportMerchantCapitalFlow'
      let downloadParam = '?token=' + this.searchForm.token + '&shopId=' + this.searchForm.shopId + '&planType=' + this.searchForm.planType
          + '&taskCode=' + this.searchForm.taskCode + '&planCode=' + this.searchForm.planCode + '&financeType=' + this.searchForm.financeType
          + '&startTime=' + this.searchForm.startTime + '&endTime=' + this.searchForm.endTime
      window.location.href = downloadUrl + downloadParam
      setTimeout(() => {
        this.$loading.hide()
        this.$message.warning('请耐心等待表格下载')
      }, 10000)
    }
  }
}
</script>

<style lang="less">
  #funding-details{

  }
  .el-popover {
    .goods-preview-img,.keyword-preview-img {
      width: 200px;
      height: 200px;
    }
  }
</style>
